package ai.zixing.pool;

import ai.zixing.config.ThreadPoolConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zixing
 *
 * 自定义线程池
 */
@Slf4j
@EnableAsync
@Configuration
public class MyDefinedThreadPool implements AsyncConfigurer {

    @Resource
    private ThreadPoolConfig config;

    @Override
    public Executor getAsyncExecutor() {
        // 创建线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(config.getCorePoolSize());
        // 最大线程数
        executor.setMaxPoolSize(config.getMaxPoolSize());
        // 阻塞队列容量
        executor.setQueueCapacity(config.getQueueCapacity());
        // 活跃时间-秒
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        // 设置线程前缀 My_Thread_
        executor.setThreadNamePrefix(config.getThreadNamePrefix());
        // 自定义线程工厂
//        executor.setThreadFactory(new MyThreadFactory());
        // 当poolSize已达到maxPoolSize，线程池拒接策略
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        executor.setRejectedExecutionHandler(new MyRejectedPolicy());
        // 不是作为Bean的时候，需要自己手动去调用initialize()方法 不然报错
        // 参考 https://blog.csdn.net/qq_41055045/article/details/115032009
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("the thread : {} Execution method {} is error : ",
                Thread.currentThread().getName(), method.getName(), ex);
    }
}

